package longshu.data.common.context;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SpringContext implements ApplicationContextAware, DisposableBean {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext context) {
        setContext(context);
    }

    public static ApplicationContext getContext() {
        if (context == null) {
            throw new RuntimeException("SpringContext 未初始化!");
        }
        return context;
    }

    public static void setContext(ApplicationContext context) {
        if (SpringContext.context != context) {
            SpringContext.context = context;
        }
    }

    /**
     * 通过name获取 Bean.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name, Object... args) {
        return (T) getContext().getBean(name, args);
    }

    /**
     * 通过class获取 Bean.
     */
    public static <T> T getBean(Class<T> clazz, Object... args) {
        return getContext().getBean(clazz, args);
    }

    @Override
    public void destroy() {
        context = null;
    }

}
